package com.castle.fortress.admin.rule.rule.service.impl;

import cn.hutool.core.util.StrUtil;
import com.castle.fortress.admin.member.member.dto.MemberDto;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.castle.fortress.admin.rule.rule.entity.RuleEntity;
import com.castle.fortress.admin.rule.rule.dto.RuleDto;
import com.castle.fortress.admin.rule.rule.mapper.RuleMapper;
import com.castle.fortress.admin.rule.rule.service.RuleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.List;
import com.castle.fortress.admin.utils.BizCommonUtil;
import java.util.Date;
import java.util.ArrayList;

/**
 * 规则表 服务实现类
 *
 * @author
 * @since 2025-04-21
 */
@Service
public class RuleServiceImpl extends ServiceImpl<RuleMapper, RuleEntity> implements RuleService {
    /**
    * 获取查询条件
    * @param ruleDto
    * @return
    */
    public QueryWrapper<RuleEntity> getWrapper(RuleDto ruleDto){
        QueryWrapper<RuleEntity> wrapper= new QueryWrapper();
        if(ruleDto != null){
            RuleEntity ruleEntity = ConvertUtil.transformObj(ruleDto,RuleEntity.class);
            wrapper.like(ruleEntity.getId() != null,"id",ruleEntity.getId());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getRuleName()),"rule_name",ruleEntity.getRuleName()).or().
            like(StrUtil.isNotEmpty(ruleEntity.getRuleName()),"rule_desc",ruleEntity.getRuleName());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getRuleDesc()),"rule_desc",ruleEntity.getRuleDesc());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getRuleType()),"rule_type",ruleEntity.getRuleType());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getRuleSource()),"rule_source",ruleEntity.getRuleSource());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getRiskLevel()),"risk_level",ruleEntity.getRiskLevel());
            wrapper.like(ruleEntity.getUpdateTime() != null,"update_time",ruleEntity.getUpdateTime());
            wrapper.like(StrUtil.isNotEmpty(ruleEntity.getMessage()),"message",ruleEntity.getMessage());
            wrapper.like(ruleEntity.getScenarioId() != null,"scenario_id",ruleEntity.getScenarioId());
            wrapper.like(ruleEntity.getCreateUser() != null,"create_user",ruleEntity.getCreateUser());
            wrapper.like(ruleEntity.getCreateTime() != null,"create_time",ruleEntity.getCreateTime());
            wrapper.like(ruleEntity.getUpdateUser() != null,"update_user",ruleEntity.getUpdateUser());
            wrapper.like(ruleEntity.getIsDeleted() != null,"is_deleted",ruleEntity.getIsDeleted());
            wrapper.orderByDesc("create_time");
        }
        return wrapper;
    }


    @Override
    public IPage<RuleDto> pageRule(Page<RuleDto> page, RuleDto ruleDto) {
        QueryWrapper<RuleEntity> wrapper = getWrapper(ruleDto);
        Page<RuleEntity> pageEntity = new Page(page.getCurrent(), page.getSize());
        //TODO 权限预留
        SysUser sysUser = WebUtil.currentUser();
        if (sysUser == null) {
            throw new RuntimeException("未登录，请检查");
        }
        // 使用嵌套条件：查询当前用户创建的规则或系统生成的规则
        wrapper.and(w -> w.eq("create_user", sysUser.getId()).or().eq("rule_source", "generate"));

        Page<RuleEntity> rulePage=baseMapper.selectPage(pageEntity,wrapper);
        Page<RuleDto> pageDto = new Page(rulePage.getCurrent(), rulePage.getSize(),rulePage.getTotal());
        pageDto.setRecords(ConvertUtil.transformObjList(rulePage.getRecords(),RuleDto.class));
        return pageDto;
    }

	@Override
	public IPage<RuleDto> pageRuleExtends(Page<RuleDto> page, RuleDto ruleDto){
		Map<String,Long> pageMap = BizCommonUtil.getPageParam(page);
          RuleEntity ruleEntity = ConvertUtil.transformObj(ruleDto,RuleEntity.class);
		List<RuleEntity> ruleList=baseMapper.extendsList(pageMap,ruleEntity);
		Long total = baseMapper.extendsCount(ruleEntity);
		Page<RuleDto> pageDto = new Page(page.getCurrent(), page.getSize(),total);
		pageDto.setRecords(ConvertUtil.transformObjList(ruleList,RuleDto.class));
		return pageDto;
	}
	@Override
	public RuleDto getByIdExtends(Long id){
          RuleEntity  ruleEntity = baseMapper.getByIdExtends(id);
		return ConvertUtil.transformObj(ruleEntity,RuleDto.class);
	}

    @Override
    public List<RuleDto> listRule(RuleDto ruleDto){
        QueryWrapper<RuleEntity> wrapper = getWrapper(ruleDto);
        List<RuleEntity> list = baseMapper.selectList(wrapper);
        return ConvertUtil.transformObjList(list,RuleDto.class);
    }

    @Override
    public boolean removeByScenarioId(Long scenarioId) {
        if (scenarioId == null) {
            return false;
        }
        QueryWrapper<RuleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("scenario_id", scenarioId);
        return this.remove(wrapper);
    }

    @Override
    public boolean removeByScenarioIds(List<Long> scenarioIds) {
        if (scenarioIds == null || scenarioIds.isEmpty()) {
            return false;
        }
        QueryWrapper<RuleEntity> wrapper = new QueryWrapper<>();
        wrapper.in("scenario_id", scenarioIds);
        return this.remove(wrapper);
    }

    @Override
    public boolean updateRuleGroup(List<Long> ids, Long scenarioId) {
        if (ids == null || ids.isEmpty() || scenarioId == null) {
            return false;
        }

        // 创建一个更新包装器
        for (Long id : ids) {
            RuleEntity rule = new RuleEntity();
            rule.setId(id);
            rule.setScenarioId(scenarioId);
            rule.setUpdateTime(new Date());
            // 更新规则的场景ID
            if (!this.updateById(rule)) {
                return false;
            }
        }

        return true;
    }

    @Override
    public List<RuleEntity> listByIds(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 构建查询条件
        QueryWrapper<RuleEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", ids)
              .eq("is_deleted", 2);
              
        return this.list(wrapper);
    }
}

